package com.gcloud.compute.handler.vm.iso;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcloud.core.handle.AsyncMessageHandler;
import com.gcloud.core.handle.Handler;
import com.gcloud.core.messagebus.MessageBus;
import com.gcloud.core.util.ErrorCodeUtil;
import com.gcloud.core.util.MessageUtil;
import com.gcloud.header.compute.msg.node.vm.iso.UnmapAndRmLnIsoCacheMsg;
import com.gcloud.header.compute.msg.node.vm.iso.UnmapAndRmLnIsoCacheReplyMsg;
import com.gcloud.header.compute.msg.node.vm.model.IsoMapItem;
import com.gcloud.header.storage.enums.StoragePoolDriver;
import com.gcloud.service.common.compute.uitls.DiskUtil;
import com.gcloud.service.common.compute.uitls.VmUtil;
import com.gcloud.service.common.util.RbdUtil;

import lombok.extern.slf4j.Slf4j;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */

@Slf4j
@Handler
public class UnmapAndRmLnIsoCacheHandler extends AsyncMessageHandler<UnmapAndRmLnIsoCacheMsg>{
	@Autowired
	private MessageBus bus;
	@Override
	public void handle(UnmapAndRmLnIsoCacheMsg msg) {
		UnmapAndRmLnIsoCacheReplyMsg replyMsg = msg.deriveMsg(UnmapAndRmLnIsoCacheReplyMsg.class);
		replyMsg.setSuccess(false);
		replyMsg.setServiceId(MessageUtil.controllerServiceId());
		replyMsg.setHostname(msg.getHostname());
		replyMsg.setIsoId(msg.getIsoId());
		try {
			//DiskUtil.rm(msg.getLnPath());
			List<IsoMapItem> mappeds = RbdUtil.getRbdmaps();
			for(IsoMapItem mapped:mappeds) {
				if(mapped.getIsoId().equals(msg.getIsoId()) && mapped.getPoolName().equals(msg.getPoolName())) {
					RbdUtil.rbdUnmap(mapped.getMapPath(), "::unrbd map失败");
				}
			}
			replyMsg.setSuccess(true);
		} catch (Exception ex) {
			log.error("unrbd map 失败", ex);
			replyMsg.setErrorCode(ErrorCodeUtil.getErrorCode(ex, "::unrbd map 失败"));
		}
		bus.send(replyMsg);
	}

}